var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
var { User, Role } = require('../model/model');

// JWT密钥
const JWT_SECRET = 'rbac-system-secret-key';

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 初始化角色
router.post('/init-roles', async function(req, res) {
  try {
    // 检查是否已经初始化
    const rolesCount = await Role.countDocuments();
    if (rolesCount > 0) {
      return res.json({ code: 200, message: '角色已经初始化' });
    }

    // 创建三种角色
    const roles = [
      {
        name: '老板',
        description: '系统最高权限',
        permissions: ['all']
      },
      {
        name: '管理员',
        description: '系统管理员',
        permissions: ['user:view', 'user:edit', 'user:add', 'user:delete', 'role:view']
      },
      {
        name: '员工',
        description: '普通员工',
        permissions: ['user:view']
      }
    ];

    await Role.insertMany(roles);
    res.json({ code: 200, message: '角色初始化成功' });
  } catch (error) {
    console.error('初始化角色失败:', error);
    res.status(500).json({ code: 500, message: '初始化角色失败', error: error.message });
  }
});

// 用户注册
router.post('/register', async function(req, res) {
  try {
    const { username, password, email, phone, sex, age, roleName } = req.body;

    // 验证必填字段
    if (!username || !password || !email) {
      return res.status(400).json({ code: 400, message: '用户名、密码和邮箱为必填项' });
    }

    // 检查用户名是否已存在
    const existingUser = await User.findOne({ username });
    if (existingUser) {
      return res.status(400).json({ code: 400, message: '用户名已存在' });
    }

    // 查找对应角色
    let role;
    if (roleName) {
      role = await Role.findOne({ name: roleName });
      if (!role) {
        return res.status(400).json({ code: 400, message: '指定的角色不存在' });
      }
    } else {
      // 默认为员工角色
      role = await Role.findOne({ name: '员工' });
      if (!role) {
        return res.status(400).json({ code: 400, message: '默认角色不存在，请先初始化角色' });
      }
    }

    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建新用户
    const newUser = new User({
      username,
      password: hashedPassword,
      email,
      phone,
      sex,
      age,
      role: role._id
    });

    await newUser.save();
    res.status(201).json({ code: 201, message: '用户注册成功' });
  } catch (error) {
    console.error('用户注册失败:', error);
    res.status(500).json({ code: 500, message: '用户注册失败', error: error.message });
  }
});

// 用户登录
router.post('/login', async function(req, res) {
  try {
    const { username, password } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({ code: 400, message: '用户名和密码为必填项' });
    }

    // 查找用户
    const user = await User.findOne({ username }).populate('role');
    if (!user) {
      return res.status(400).json({ code: 400, message: '用户名或密码错误' });
    }

    // 检查账号状态
    if (!user.status) {
      return res.status(403).json({ code: 403, message: '账号已被禁用' });
    }

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(400).json({ code: 400, message: '用户名或密码错误' });
    }

    // 生成JWT令牌
    const payload = {
      user: {
        id: user._id,
        username: user.username,
        role: user.role.name,
        permissions: user.role.permissions
      }
    };

    jwt.sign(
      payload,
      JWT_SECRET,
      { expiresIn: '24h' },
      (err, token) => {
        if (err) throw err;
        res.json({
          code: 200,
          message: '登录成功',
          token,
          user: {
            id: user._id,
            username: user.username,
            email: user.email,
            role: user.role.name,
            permissions: user.role.permissions
          }
        });
      }
    );
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ code: 500, message: '登录失败', error: error.message });
  }
});

// 验证Token中间件
const authMiddleware = (req, res, next) => {
  // 获取token
  const token = req.header('x-auth-token');

  // 检查是否有token
  if (!token) {
    return res.status(401).json({ code: 401, message: '无访问权限，请先登录' });
  }

  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ code: 401, message: '无效的Token' });
  }
};

// 获取当前用户信息
router.get('/me', authMiddleware, async (req, res) => {
  try {
    const user = await User.findById(req.user.id).select('-password').populate('role');
    if (!user) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    res.json({
      code: 200,
      user: {
        id: user._id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        sex: user.sex,
        age: user.age,
        role: user.role.name,
        permissions: user.role.permissions,
        status: user.status,
        createTime: user.createTime
      }
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ code: 500, message: '获取用户信息失败', error: error.message });
  }
});

module.exports = router;
